<?php
/* explain:		news system
 * Project:     
 * File:        news.php
 *
 * @ link 		http://www.../modules/
 * @ Email		ldmmyx@hotmail.com
 * @ copyright 	2005  Ling Deming
 * @ author 	ivan.ling  Ling Deming
 * @ version 	1.0
 *
 */
include_once("Common.php");
include_once("domain/CouponDomain.php");
include_once("domain/CouponImageDomain.php");
include_once("dao/CouponDAO.php");
include_once("dao/CommonDAO.php");
include_once("constant/GlobalConstant.php");

include_once("utils/StringUtils.php");
include_once("utils/CouponUtils.php");

class CouponImpl extends Common implements CouponDAO, CommonDAO
{
	private $conn;
	private $message;
	

	function CouponImpl($DBTag)
	{
		parent::Common();
		
		$this->conn = $this->getConnection($DBTag);
		
	}

	/* get data via ID
	 *
	 * @param  int    id
	 * @return mixed  false:
	 */
	public function getById($id) 
	{
		$sql  = 'SELECT id, merchantId, code, name, descript, trackingURL, trackingHtmlCode, startDate, endDate, ';
		$sql .= "sourceId, creativeType, costType, isFeatured, isRecommend, impressionpixel FROM coupon WHERE id = $id";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($row = mysql_fetch_row($rs)) {
				$coupon = new CouponDomain();

				$coupon->setId($row[0]);
				$coupon->setMerchantId($row[1]);
				$coupon->setCode($row[2]);
				$coupon->setName($row[3]);
				$coupon->setDescript($row[4]);
				
				$coupon->setTrackingURL($row[5]);
				$coupon->setTrackingHtmlCode($row[6]);
				
				$coupon->setStartDate($row[7]);
				$coupon->setEndDate($row[8]);

				$coupon->setSourceId($row[9]);
				$coupon->setCreativeType($row[10]);
				
				$coupon->setCostType($row[11]);
				
				$coupon->setIsFeatured($row[12]);
				$coupon->setIsRecommend($row[13]);
				$coupon->setImpressionpixel($row[13]);
				
				return $coupon;
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return null;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return null;
		}
	}

	public function add($coupon)
	{
		if($coupon instanceof CouponDomain){
			$IDkey = md5($coupon->getMerchantId() . $coupon->getCode() . $coupon->getName() . $coupon->getDescript());
			
			if($this->isExisted($IDkey)){
//				echo "repeat id key : " . $IDkey;
//				echo "\n";
				
				return 0;
			}
			
			$sql 	 = "INSERT INTO coupon SET createdTime = UTC_TIMESTAMP(), modifiedTime = UTC_TIMESTAMP()";
			
			$descript = $coupon->getDescript();
			if(!empty($descript)){
				$sql	.= ", descript='";
				$sql	.= addslashes($descript);
				$sql	.= "'";
			}
			
			$sql 	.= ", name='";
			$sql	.= addslashes($coupon->getName());
	
			$sql 	.= "', merchantId=";
			$sql	.= $coupon->getMerchantId();
	
			$sql 	.= ", sourceId=";
			$sql	.= $coupon->getSourceId();

			$startDate = $coupon->getStartDate();
			if(!empty($startDate)){
				$sql	.= ", startDate='";
				$sql	.= date('Y-m-d', strtotime($startDate));
				$sql	.= "'";
			}
			
			$endDate = $coupon->getEndDate();
			if(!empty($endDate)){
				$sql	.= ", endDate='";
				$sql	.= date('Y-m-d', strtotime($endDate));
				$sql	.= "'";
			}
			
			$sql	.= ", creativeType='";
			$sql	.= $coupon->getCreativeType();

			$sql	.= "', code='";
			$sql	.= $coupon->getCode();

			$sql	.= "', costType='";
			$sql	.= $coupon->getCostType();

			$sql	.= "', trackingURL='";
			$sql	.= $coupon->getTrackingURL();
			$sql	.= "'";
			
			$sql	.= ", IDkey='";
			$sql	.= $IDkey;
			
			$sql	.= "', status=";
			$sql	.= $coupon->getStatus();
			$sql	.= " ON DUPLICATE KEY UPDATE modifiedTime=Values(modifiedTime)";
			
			$id		= 0;
			
			try{
				$rs  	= mysql_query($sql, $this->conn);
				if($rs){
					$id = mysql_insert_id($this->conn);
					
					$coupon->setId($id);
					
					$couponImg = $coupon->getCouponImage();
					if(is_object($couponImg)){
						$coupon->getCouponImage()->setCouponId($id);
					
						$this->addImage($coupon->getCouponImage());						
					}
					
					$this->messages = "add successfully. id = $id";
				}else{
					$this->messages  = "add failed. sql : $sql . <br>";
					$this->messages .= "error: " .  mysql_error($this->conn);
				}
			}catch(Exception $e){
				$this->messages = $e->getMessage();
				
				$id	= -1;
			}
		}else{
			$id	= -1;
			
			$this->message = 'input object is not instance of CouponDomain.';
		}
			
		return $id;
	}
	
	public function addAttribute($couponId, $attributeId, $attributeValue)
	{
		$sql 	 = "INSERT INTO coupon_attributes SET couponId=";
		$sql	.= $couponId;
		
		$sql 	.= ", attributeId=";
		$sql	.= $attributeId;
		
		$sql 	.= ", attributeValue='";
		$sql	.= addslashes($attributeValue);

		$sql	.= "' ON DUPLICATE KEY UPDATE attributeValue=Values(attributeValue)";
		
		try{
			$rs  	= mysql_query($sql, $this->conn);
			if($rs){
				$this->messages = "add successfully.";
			}else{
				$this->messages  = "add failed. sql : $sql . <br>";
				$this->messages .= "error: " .  mysql_error($this->conn);
			}
		}catch(Exception $e){
			$this->messages = $e->getMessage();
			
			$id	= -1;
		}
	}	
		
	public function addCategory($couponId, $categoryId)
	{
		$sql 	 = "INSERT INTO coupon_category SET couponId=";
		$sql	.= $couponId;
		
		$sql 	.= ", categoryId=";
		$sql	.= $categoryId;

		$sql	.= " ON DUPLICATE KEY UPDATE couponId=Values(couponId)";
		
		try{
			$rs  	= mysql_query($sql, $this->conn);
			if($rs){
				$this->messages = "add successfully.";
			}else{
				$this->messages  = "add failed. sql : $sql . <br>";
				$this->messages .= "error: " .  mysql_error($this->conn);
			}
		}catch(Exception $e){
			$this->messages = $e->getMessage();
			
			$id	= -1;
		}
	}
	
	public function addImage($couonImage)
	{
		if($couonImage instanceof CouponImageDomain){
			$sql 	 = "INSERT INTO coupon_images SET modifiedTime = UTC_TIMESTAMP(), couponId=";
			$sql	.= $couonImage->getCouponId();
			
			$sql 	.= ", name='";
			$sql	.= addslashes($couonImage->getName());
	
			$sql 	.= "', impressionTrackingUrl='";
			$sql	.= $couonImage->getImpressionTrackingUrl();

			$sql	.= "', imageAltText='";
			$sql	.= addslashes($couonImage->getImageAltText());

			$sql	.= "', width='";
			$sql	.= $couonImage->getWidth();

			$sql	.= "', height='";
			$sql	.= $couonImage->getHeight();

			$sql	.= "', useType='";
			$sql	.= $couonImage->getUseType();
				
			$sql	.= "', status=";
			$sql	.= $couonImage->getStatus();
			$sql	.= " ON DUPLICATE KEY UPDATE modifiedTime=Values(modifiedTime)";
			
			try{
				$rs  	= mysql_query($sql, $this->conn);
				if($rs){
					$this->messages = "add successfully.";
				}else{
					$this->messages  = "add failed. sql : $sql . <br>";
					$this->messages .= "error: " .  mysql_error($this->conn);
				}
			}catch(Exception $e){
				$this->messages = $e->getMessage();
				
				$id	= -1;
			}
		}else{
			$id	= -1;
			
			$this->message = 'input object is not instance of CouponDomain.';
		}
	}
	
	/* delete news class
	 *
	 * @param  int    	id
	 * @param  string  	status
	 * @param  return 	boolean
	 */
	public function delete($id)
	{
		$sql = "DELETE FROM coupon WHERE id = $id";
		
		$rs	 = mysql_query($sql, $this->conn) or die (mysql_error());
		if($rs)
			return true;
		else
			return false;
	}
	
	public function isExisted($IDkey)
	{
		$sql  = "SELECT id FROM coupon WHERE IDKey = '$IDkey'";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($row = mysql_fetch_row($rs)) {
				return true;
			} else {
				return false;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return false;
		}
	}
	
	public function setFeatured($couponId, $r_sortValue, $isFeatured = 1) 
	{
		$sql  = "UPDATE coupon SET isFeatured = $isFeatured, r_sortValue = $r_sortValue WHERE id = $couponId";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($rs){
				return true;
			} else {
				$this->messages = "set coupon isFeatured failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return false;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return false;
		}
	}
	
	public function setFeaturedByMerchantId($merchantId, $isFeatured = 0) 
	{
		$sql  = "UPDATE coupon SET isFeatured = $isFeatured, r_sortValue = 0 WHERE merchantId = $merchantId";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($rs){
				return true;
			} else {
				$this->messages = "set coupon isFeatured failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return false;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return false;
		}
	}
	
	public function getCouponImage($couponId, $useType = 1) 
	{
		$sql  = 'SELECT id, name, width, height, useType, impressionTrackingUrl, imageAltText ';
		$sql .= "FROM coupon_images WHERE couponId = $couponId AND useType = $useType";
		
		try {
			$rs = mysql_query($sql, $this->conn);
			if ($row = mysql_fetch_row($rs)) {
				$coupon = new CouponImageDomain();
				$coupon->setCouponId($couponId);
				
				$coupon->setId($row[0]);
				$coupon->setName($row[1]);
				$coupon->setWidth($row[2]);
				$coupon->setHeight($row[3]);
				$coupon->setUseType($row[4]);
				$coupon->setImpressionTrackingUrl($row[5]);
				$coupon->setImageAltText($row[6]);

				return $coupon;
			} else {
				$this->messages = "get coupon data failed by Id. sql : $sql <br>";
				$this->messages .= "error: " . mysql_error($this->conn);

				return null;
			}
		} catch (Exception $e) {
			$this->messages = $e->getMessage();

			return null;
		}
	}
	
	public function getCoupons($page = 0, $discount = 20)
	{
		//TODO remove sort
		return $this->getCustoms(" WHERE status = 1", " order by id desc", $page, $discount);
	}
	
	public function getCouponsByMerchant($merchantId, $page = 0, $discount = 20, $order = " ORDER BY startDate DESC, r_sortValue DESC")
	{
		return $this->getCustoms(" WHERE status = 1 AND isFeatured != 1 AND merchantId = $merchantId", $order, $page, $discount);
	}
	
	public function getFeaturedCouponsByMerchant($merchantId, $page = 0, $discount = 20, $order = " ORDER BY startDate DESC, r_sortValue DESC")
	{
		//TODO remove sort
		return $this->getCustoms(" WHERE status = 1 AND isFeatured = 1 AND merchantId = $merchantId", $order, $page, $discount);
	}
	
	public function getCouponsByTag($tagId, $page = 0, $discount = 20, $order = " order by id desc")
	{
		//TODO remove sort
		return $this->getCustoms(" WHERE status = 1 AND id IN (SELECT couponId FROM coupon_tag WHERE authorized = 1 AND tagId = $tagId)", $order, $page, $discount);
	}
	
	public function getAll()
	{
		return $this->getCustoms(" WHERE status = 1", '', 0, 0);
	}
	
	public function getCustoms($where, $order, $page = 0, $discount = 20)
	{
		$arrback = array();
		
		try{
			$sql = "SELECT count(1) FROM coupon $where";
			
			$rs  = mysql_query($sql, $this->conn);
			
			list($total) = mysql_fetch_row($rs);
			
			$this->mutilPager($total, $page, $discount);
			if(!empty($total)){
				$sql  = 'SELECT id, merchantId, code, name, descript, trackingURL, trackingHtmlCode, startDate, endDate, ';
				$sql .= "sourceId, creativeType, costType, isFeatured, isRecommend, impressionpixel FROM coupon $where $order";
				
				if($discount > 0)
					$sql .= " LIMIT $this->firstcount, $discount";
				
				$rs  = mysql_query($sql, $this->conn);
				if($rs){
					while($row = mysql_fetch_array($rs)){
						$coupon = new CouponDomain();

						$coupon->setId($row[0]);
						$coupon->setMerchantId($row[1]);
						$coupon->setCode($row[2]);
						$coupon->setName($row[3]);
						$coupon->setDescript($row[4]);
						
						$coupon->setTrackingURL($row[5]);
						$coupon->setTrackingHtmlCode($row[6]);
						
						$coupon->setStartDate($row[7]);
						$coupon->setEndDate($row[8]);
						
						$coupon->setSourceId($row[9]);
						$coupon->setCreativeType($row[10]);						
						
						$coupon->setCostType($row[11]);
						
						$coupon->setIsFeatured($row[12]);
						$coupon->setIsRecommend($row[13]);
						
						$coupon->setImpressionpixel($row[14]);
						
						
						$arrback[] = $coupon;
					}
				}else {
					$this->message = "select failed. sql : $sql";
					$this->message .= "<br>error: " . mysql_error($this->conn);

				}
			}
		}catch(Exception $e){
			$this->message = $e->getMessage();
			
			return null;
		}
		
		return $arrback;
	}
	
	public function getCouponByGoogleLink($merchantId, $link)
	{
		$creativeType 	= $this->convertToCreative($link);
		$couponCode		= $this->pasreCouponCode($link);		
		
		$oC = new CouponDomain();		
		
		$oC->setMerchantId($merchantId);
		$oC->setCode($couponCode);
		$oC->setName($link->getName());
		$oC->setDescript($link->getDescription());
		
		$oC->setTrackingURL($link->getClickTrackingUrl);
		$oC->setTrackingHtmlCode('');
		
		$oC->setStartDate($link->getStartDate());
		$oC->setEndDate($link->getEndDate());
		
		$oC->setSourceId(GlobalConstant::SOURCE_ID_GOOGLE);
		$oC->setCreativeType($creativeType);
		
		$oC->setimpressionTrackingUrl($link->getImpressionTrackingUrl());
		
		$oC->setCostType(GlobalConstant::COST_TYPE_CPA);
		
		$oC->setIsFeatured(0);
		$oC->setIsRecommend(0);
	}
	
	private function convertToCreative($link)
	{
		$creativeType = $link->getLinkType();
		
		if($creativeType == 'BANNER'){
			$creativeType = '1';
		}else if ($creativeType == 'TEXT'){
			$creativeType = '2';
		}else if ($creativeType == 'SEARCH BOX'){
			$creativeType = '3';			
		}else
			$creativeType = '2';
			
		return $creativeType;
	}
	
	private function pasreCouponCode($link)
	{
		$code = '';
		
		if ($link->getPromotionType() == 'COUPON'){
			$startFlag 	= 'with coupon code ';
			$endFlag	= '. expirat';
			
			$code 	= StringUtils::getCutValue($startFlag, $endFlag, $link->getName());
			$name 	= StringUtils::getStartValue(' with coupon code', $link->getName());
		}
		
		if(empty($code)){
			$code = CouponUtils::findCode($link->getName());		
		}
		
		return $code;
	}
	
	public function getMessage() 
	{
		return $this->message;
	}
	
}
?>
